@extends('layouts.app')

@section('title', $title)

@push('styles')
<style>
    /* 页面基础样式 */
    body {
        background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
        margin: 0;
        padding: 0;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        min-height: 100vh;
    }

    .container {
        max-width: 100%;
        padding: 0;
        margin: 0;
        background: white;
        min-height: 100vh;
    }

    /* 顶部导航栏样式 */
    .header-nav {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: rgba(255,255,255,0.95);
        backdrop-filter: blur(20px);
        padding: 12px 15px;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        box-shadow: 0 2px 20px rgba(0,0,0,0.05);
        position: sticky;
        top: 0;
        z-index: 100;
    }

    .category-title {
        font-size: 18px;
        font-weight: 700;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        text-align: center;
        flex: 1;
    }

    /* 时间显示样式 */
    .time-summary-section {
        margin: 0;
        background: white;
        padding: 15px;
        border-bottom: 1px solid #e2e8f0;
    }

    .current-period {
        text-align: center;
        margin-bottom: 12px;
    }

    .period-display {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        cursor: pointer;
        padding: 8px 12px;
        border-radius: 8px;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .period-display:hover {
        background: #f1f5f9;
    }

    .period-arrow {
        font-size: 12px;
        transition: transform 0.3s ease;
    }

    .period-display.active .period-arrow {
        transform: rotate(180deg);
    }

    /* 统计周期切换样式 */
    .period-tabs {
        display: flex;
        background: #f8fafc;
        border-radius: 12px;
        padding: 4px;
        border: 1px solid #e2e8f0;
    }

    .period-tab {
        padding: 8px 16px;
        border: none;
        background: transparent;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        color: #64748b;
        min-width: 50px;
    }

    .period-tab:hover {
        color: #667eea;
    }

    .period-tab.active {
        background: white;
        color: #667eea;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
        border: 1px solid #e2e8f0;
    }

    /* 时间选择切换样式 */
    .time-tabs {
        background: white;
        padding: 12px 0;
        border-bottom: 1px solid #e2e8f0;
        display: flex;
        align-items: center;
        position: relative;
    }

    .time-tabs-container {
        display: flex;
        padding: 0 5px;
        gap: 4px;
        flex: 1;
        overflow-x: auto;
        overflow-y: hidden;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* IE and Edge */
        scroll-behavior: smooth;
        margin: 0 40px; /* 为左右按钮留出空间 */
        /* 增强的滑动支持 */
        touch-action: pan-x;
        overscroll-behavior-x: contain;
        scroll-snap-type: x proximity;
    }

    .time-tabs-container::-webkit-scrollbar {
        display: none; /* Chrome, Safari, Opera */
    }

    /* 滑动指示器 */
     .time-tabs {
         --show-left-indicator: 0;
         --show-right-indicator: 1;
     }
     .time-tabs::before,
     .time-tabs::after {
         content: '';
         position: absolute;
         top: 0;
         bottom: 0;
         width: 20px;
         pointer-events: none;
         z-index: 5;
         transition: opacity 0.3s ease;
     }

     .time-tabs::before {
         left: 40px;
         background: linear-gradient(to right, rgba(255,255,255,0.9), transparent);
         opacity: var(--show-left-indicator);
     }

     .time-tabs::after {
         right: 40px;
         background: linear-gradient(to left, rgba(255,255,255,0.9), transparent);
         opacity: var(--show-right-indicator);
     }

    .time-nav-btn {
        background: rgba(255, 255, 255, 0.95);
        border: 1px solid #e2e8f0;
        font-size: 18px;
        color: #667eea;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        flex-shrink: 0;
        transition: all 0.2s ease;
        border-radius: 50%;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        z-index: 10;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .time-nav-btn:hover {
        background: #667eea;
        color: white;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .time-nav-btn:active {
        transform: translateY(-50%) scale(0.95);
    }

    #prev-period {
        left: 10px;
    }

    #next-period {
        right: 10px;
    }

    .time-tab {
        padding: 8px 12px;
        border: none;
        background: transparent;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;
        color: #64748b;
        white-space: nowrap;
        flex-shrink: 0;
        position: relative;
        /* 滚动吸附 */
        scroll-snap-align: center;
        min-width: 60px;
        text-align: center;
    }

    .time-tab:hover {
        color: #667eea;
        background: rgba(102, 126, 234, 0.05);
    }

    .time-tab.active {
        color: #667eea;
        font-weight: 600;
        background: rgba(102, 126, 234, 0.1);
    }

    .time-tab.active::after {
        content: '';
        position: absolute;
        bottom: -12px;
        left: 50%;
        transform: translateX(-50%);
        width: 20px;
        height: 3px;
        background: #667eea;
        border-radius: 2px;
    }

    /* 图表容器样式 */
    .chart-section {
        background: white;
        border-bottom: 1px solid #e2e8f0;
    }

    .chart-title {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 16px;
    }

    .chart-container {
        position: relative;
        height: 250px;
        margin: 15px 0;
        padding: 20px;
        border: none;
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.06);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .chart-left {
            width: 50%;
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .chart-middle {
            width: 25%;
            display: none;
        }

        .chart-right {
            width: 45%;
            height: 200px;
            overflow-y: auto;
            padding-left: 15px;
        }

    .total-amount {
        text-align: center;
    }

    .amount-value {
        font-size: 24px;
        font-weight: bold;
        color: #1e293b;
        margin-bottom: 5px;
    }

    .amount-label {
        font-size: 14px;
        color: #64748b;
        font-weight: 500;
    }

    .color-legend {
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .legend-item {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 12px;
        color: #374151;
    }

    .legend-color {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        flex-shrink: 0;
    }

    .legend-text {
        flex: 1;
        line-height: 1.2;
    }

    /* 记录列表样式 */
    .records-section {
        background: white;
        margin: 10px 10px;
        border-radius: 16px;
        padding: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid rgba(0,0,0,0.05);
    }

    .records-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }

    .records-title {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
    }

    .sort-dropdown {
        position: relative;
    }

    .sort-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 10px 16px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .sort-btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
    }

    .sort-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background: white;
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
        z-index: 1000;
        margin-top: 8px;
        overflow: hidden;
        display: none;
        min-width: 120px;
    }

    .sort-option {
        padding: 12px 16px;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 15px;
        font-weight: 500;
        color: #374151;
    }

    .sort-option:hover {
        background: #f8fafc;
    }

    .sort-option.active {
        background: #667eea;
        color: white;
    }

    /* 记录项样式 */
    .record-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 18px 0;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        transition: all 0.2s ease;
    }

    .record-item:hover {
        background: rgba(102, 126, 234, 0.02);
        margin: 0 -20px;
        padding: 18px 20px;
        border-radius: 8px;
    }

    .record-item:last-child {
        border-bottom: none;
    }

    .record-info {
        flex: 1;
    }

    .record-desc {
        font-size: 15px;
        font-weight: 500;
        color: #1e293b;
        margin-bottom: 4px;
    }

    .record-time {
        font-size: 13px;
        color: #64748b;
    }

    .record-amount {
        font-size: 16px;
        font-weight: 600;
        color: #ef4444;
    }

    .record-amount.income {
        color: #10b981;
    }

    /* 展开/收起按钮 */
    .toggle-btn {
        display: block;
        width: 100%;
        padding: 12px;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        border: 1px solid rgba(0,0,0,0.05);
        border-radius: 12px;
        color: #667eea;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        margin-top: 16px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }

    .toggle-btn:hover {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    /* 二级分类统计样式 */
    .subcategory-section {
        padding: 0 20px;
    }

    .subcategory-title {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        margin-bottom: 16px;
    }

    .subcategory-ranking-list {
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid rgba(0,0,0,0.05);
    }

    .subcategory-item {
        display: flex;
        align-items: center;
        padding: 18px 20px;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        transition: all 0.2s ease;
        cursor: pointer;
    }

    .subcategory-item:hover {
        background: rgba(102, 126, 234, 0.02);
    }

    .subcategory-item:last-child {
        border-bottom: none;
    }

    .subcategory-rank {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        margin-right: 16px;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .subcategory-rank.top1 {
        background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
        color: #92400e;
        box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
    }

    .subcategory-rank.top2 {
        background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
        color: #374151;
        box-shadow: 0 4px 12px rgba(209, 213, 219, 0.4);
    }

    .subcategory-rank.top3 {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: white;
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
    }

    .subcategory-rank.other {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        color: #64748b;
        box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    }

    .subcategory-info {
        flex: 1;
    }

    .subcategory-name {
        font-size: 15px;
        font-weight: 500;
        color: #1e293b;
        margin-bottom: 4px;
    }

    .subcategory-percent {
        font-size: 13px;
        color: #64748b;
    }

    .subcategory-amount {
        font-size: 16px;
        font-weight: 600;
        color: #ef4444;
    }

    .subcategory-amount.income {
        color: #10b981;
    }

    /* 分类统计汇总样式 */
    .category-summary-section {
        margin: 0;
        background: white;
        padding: 15px;
        border-bottom: 1px solid #e2e8f0;
    }

    .summary-stats {
        display: flex;
        justify-content: space-around;
        gap: 10px;
    }

    .summary-item {
        text-align: center;
        flex: 1;
    }

    .summary-amount {
        font-size: 18px;
        font-weight: 700;
        margin-bottom: 2px;
        color: #1e293b;
    }

    .summary-amount.category-total {
        color: #ef4444;
    }

    .summary-amount.category-count {
        color: #667eea;
    }

    .summary-amount.category-avg {
        color: #10b981;
    }

    .summary-label {
        font-size: 11px;
        color: #64748b;
        font-weight: 500;
    }

    /* 隐藏的记录项 */
    .record-item.hidden {
        display: none;
    }

    /* 底部空间 */
    .bottom-space {
        height: 20px;
    }

    .back-btn {
        color: #667eea;
        box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
        border: 1px solid #e2e8f0;
        background: #f8fafc;
    }

    /* 排行榜样式 */
    .ranking-section {
        background: white;
        padding: 10px 10px 0px 10px;
    }

    .ranking-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .ranking-title {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
    }

    .ranking-list {
        background: white;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 20px rgba(0,0,0,0.08);
        border: 1px solid rgba(0,0,0,0.05);
    }

    .ranking-item {
        display: flex;
        align-items: center;
        padding: 18px 20px;
        border-bottom: 1px solid rgba(0,0,0,0.05);
        transition: all 0.2s ease;
        cursor: pointer;
    }

    .ranking-item:hover {
        background: rgba(102, 126, 234, 0.02);
    }

    .ranking-item:last-child {
        border-bottom: none;
    }

    .ranking-rank {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        margin-right: 16px;
        font-size: 14px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .ranking-rank.top1 {
        background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
        color: #92400e;
        box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
    }

    .ranking-rank.top2 {
        background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
        color: #374151;
        box-shadow: 0 4px 12px rgba(209, 213, 219, 0.4);
    }

    .ranking-rank.top3 {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        color: white;
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
    }

    .ranking-rank.other {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        color: #64748b;
        box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    }

    .ranking-info {
        flex: 1;
    }

    .ranking-name {
        font-weight: 600;
        margin-bottom: 4px;
        color: #1e293b;
        font-size: 15px;
    }

    .ranking-percent {
        font-size: 12px;
        color: #64748b;
        font-weight: 500;
    }

    .ranking-amount {
        font-weight: 700;
        color: #1e293b;
        font-size: 16px;
    }

    .ranking-section .chart-container {
        margin: 0;
        background: transparent;
        border-radius: 0;
        padding: 0;
        box-shadow: none;
        border: none;
    }
</style>
@endpush

@section('content')
<div class="container">
    <!-- 顶部导航栏 -->
    <div class="header-nav">
        <button class="back-btn" onclick="history.back()">‹</button>
        <div class="category-title" id="category-title">{{ $categoryName }}</div>
        <div class="period-tabs">
            <button class="period-tab {{ $periodType == 'week' ? 'active' : '' }}" data-period="week">周</button>
            <button class="period-tab {{ ($periodType ?? 'month') == 'month' ? 'active' : '' }}" data-period="month">月</button>
            <button class="period-tab {{ $periodType == 'year' ? 'active' : '' }}" data-period="year">年</button>
        </div>
    </div>

    <!-- 时间选择切换 -->
    <div class="time-tabs">
        <button class="time-nav-btn" id="prev-period">‹</button>
        <div class="time-tabs-container" id="time-tabs-container">
            <!-- 动态生成时间选择标签 -->
        </div>
        <button class="time-nav-btn" id="next-period">›</button>
    </div>

    <!-- 分类统计汇总 -->
    <div class="category-summary-section">
            <!-- 时间显示 -->
        <div class="current-period">
            <div class="period-display" id="period-display">{{ date('Y年n月') }}</div>
        </div>
        <div class="summary-stats">
            <div class="summary-item">
                <div class="summary-amount category-total" id="category-total">0</div>
                <div class="summary-label">总计</div>
            </div>
            <div class="summary-item">
                <div class="summary-amount category-count" id="category-count">0</div>
                <div class="summary-label">笔数</div>
            </div>
            <div class="summary-item">
                <div class="summary-amount category-avg" id="category-avg">0</div>
                <div class="summary-label">平均</div>
            </div>
        </div>
    </div>

    <!-- 折线图统计 -->
    <div class="chart-section">
        <canvas id="trend-chart"></canvas>
    </div>

        <!-- 二级分类统计（仅一级分类显示） -->
    <div class="ranking-section" id="subcategory-ranking-section" style="display: none;">
        <div class="ranking-header">
            <div class="ranking-title">下级分类排行</div>
        </div>

        <!-- 饼图统计 -->
        <div class="chart-container">
            <div class="chart-left">
                <canvas id="subcategory-pie-chart"></canvas>
            </div>
            <div class="chart-middle">
                <div class="total-amount">
                    <div class="amount-value" id="subcategory-total-amount">0</div>
                    <div class="amount-label">总计</div>
                </div>
            </div>
            <div class="chart-right">
                <div class="color-legend" id="subcategory-legend">
                    <!-- 颜色说明项，通过JavaScript动态生成 -->
                </div>
            </div>
        </div>

        <div class="ranking-list" id="subcategory-list">
            <!-- 动态生成二级分类排行榜 -->
        </div>
    </div>

    <!-- 记账记录列表 -->
    <div class="records-section">
        <div class="records-header">
            <div class="records-title">记账记录</div>
            <div class="sort-dropdown">
                <button class="sort-btn" id="sort-btn">
                    <span id="sort-text">按金额</span>
                    <span>▼</span>
                </button>
                <div class="sort-menu" id="sort-menu">
                    <div class="sort-option active" data-sort="amount">按金额</div>
                    <div class="sort-option" data-sort="time">按时间</div>
                </div>
            </div>
        </div>
        <div class="records-list" id="records-list">
            <!-- 动态生成记录列表 -->
        </div>
        <button class="toggle-btn" id="toggle-btn">查看更多</button>
    </div>

    <div class="bottom-space"></div>
</div>
@endSection

@push('scripts')
    <script src="{{ asset('/js/chart.js') }}"></script>
    <script>
        // 全局变量
        let currentPeriod = '{{ $periodType ?? "month" }}';
        let currentPeriodValue = '{{ $periodValue ?? "" }}';
        let currentSortType = 'amount';
        let isExpanded = false;
        let trendChart = null;
        let subcategoryPieChart = null;
        let categoryId = {{ $categoryId }};
        let categoryName = '{{ $categoryName }}';
        let categoryType = '{{ $categoryType }}';
        let categoryLevel = {{ $categoryLevel }};
        let isLevel1 = categoryLevel == 1;

        // 时间导航变量
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        let currentWeek = Math.ceil(new Date().getDate() / 7);
        let currentStartDate = '';
        let currentEndDate = '';

        // 滚动到选中的时间标签
        function scrollToActiveTab() {
            const container = document.getElementById('time-tabs-container');
            const activeTab = container.querySelector('.time-tab.active');

            if (activeTab && container) {
                const tabLeft = activeTab.offsetLeft;
                const tabWidth = activeTab.offsetWidth;
                const containerWidth = container.clientWidth;
                const scrollLeft = container.scrollLeft;

                // 如果标签在可视区域外，则滚动到合适位置
                if (tabLeft < scrollLeft) {
                    // 标签在左侧不可见，滚动到标签位置
                    container.scrollLeft = tabLeft - 20;
                } else if (tabLeft + tabWidth > scrollLeft + containerWidth) {
                    // 标签在右侧不可见，滚动到标签可见
                    container.scrollLeft = tabLeft + tabWidth - containerWidth + 20;
                }
            }
        }

        // 生成时间选择标签
        function generateTimeTabs() {
            const container = document.getElementById('time-tabs-container');
            container.innerHTML = '';

            let tabs = [];
            const currentDate = new Date();
            const currentRealYear = currentDate.getFullYear();
            const currentRealMonth = currentDate.getMonth() + 1;
            const currentRealWeek = Math.ceil(currentDate.getDate() / 7);

            if (currentPeriod === 'week') {
                // 周统计：显示当前月的几个周
                const firstDay = new Date(currentYear, currentMonth - 1, 1);
                const lastDay = new Date(currentYear, currentMonth, 0);

                // 找到当月第一个周一
                const firstMonday = new Date(firstDay);
                const dayOfWeek = firstDay.getDay(); // 0=周日, 1=周一, ..., 6=周六
                const daysToMonday = dayOfWeek === 0 ? 1 : (8 - dayOfWeek); // 如果是周日，需要1天到周一；其他情况计算到下一个周一的天数
                if (dayOfWeek !== 1) { // 如果第一天不是周一
                    firstMonday.setDate(firstDay.getDate() + daysToMonday);
                }

                // 计算当月有多少个完整的周（从周一开始）
                let weekCount = 0;
                let currentWeekStart = new Date(firstMonday);

                while (currentWeekStart <= lastDay) {
                    weekCount++;
                    currentWeekStart.setDate(currentWeekStart.getDate() + 7);
                }

                // 限制到当前周（如果是当前月份和当前年份）
                let maxWeek = weekCount;

                // 如果是当前年份和当前月份，限制到当前周
                if (currentYear === currentRealYear && currentMonth === currentRealMonth && currentRealWeek > 0) {
                    maxWeek = Math.min(weekCount, currentRealWeek);
                }

                // 确保当前选中的周不超过最大周数
                if (currentWeek > maxWeek) {
                    currentWeek = maxWeek;
                }

                for (let week = 1; week <= maxWeek; week++) {
                    const startDate = new Date(firstMonday);
                    startDate.setDate(startDate.getDate() + (week - 1) * 7);
                    const endDate = new Date(startDate);
                    endDate.setDate(startDate.getDate() + 6);

                    const weekValue = `${currentYear}-${currentMonth.toString().padStart(2, '0')}-${week}`;
                    // 如果有URL传入的period_value，优先使用它来判断是否激活
                    const isActive = currentPeriodValue ? (weekValue === currentPeriodValue) : (week === currentWeek);

                    tabs.push({
                        text: `第${week}周`,
                        value: weekValue,
                        startDate: startDate.toISOString().split('T')[0],
                        endDate: endDate.toISOString().split('T')[0],
                        active: isActive
                    });

                    if (isActive) {
                        currentPeriodValue = weekValue;
                    }
                }
            } else if (currentPeriod === 'month') {
                // 月统计：显示当前年的12个月
                for (let month = 1; month <= 12; month++) {
                    const startDate = new Date(currentYear, month - 1, 1);
                    const endDate = new Date(currentYear, month, 0);

                    const monthValue = `${currentYear}-${month.toString().padStart(2, '0')}`;
                    // 如果有URL传入的period_value，优先使用它来判断是否激活
                    const isActive = currentPeriodValue ? (monthValue === currentPeriodValue) : (month === currentMonth);

                    tabs.push({
                        text: `${month}月`,
                        value: monthValue,
                        startDate: startDate.toISOString().split('T')[0],
                        endDate: endDate.toISOString().split('T')[0],
                        active: isActive
                    });

                    if (isActive) {
                        currentPeriodValue = monthValue;
                    }
                }
            } else {
                // 年统计：显示当前年+往前4年一共5年
                const startYear = currentYear - 4;
                const endYear = currentYear;

                for (let year = startYear; year <= endYear; year++) {
                    const startDate = new Date(year, 0, 1);
                    const endDate = new Date(year, 11, 31);

                    const yearValue = year.toString();
                    // 如果有URL传入的period_value，优先使用它来判断是否激活
                    const isActive = currentPeriodValue ? (yearValue === currentPeriodValue) : (year === currentYear);

                    tabs.push({
                        text: `${year}年`,
                        value: yearValue,
                        startDate: startDate.toISOString().split('T')[0],
                        endDate: endDate.toISOString().split('T')[0],
                        active: isActive
                    });

                    if (isActive) {
                        currentPeriodValue = yearValue;
                    }
                }
            }

            tabs.forEach(tab => {
                const tabElement = document.createElement('button');
                tabElement.className = `time-tab ${tab.active ? 'active' : ''}`;
                tabElement.textContent = tab.text;
                tabElement.setAttribute('data-time', tab.value);
                tabElement.setAttribute('data-start-date', tab.startDate);
                tabElement.setAttribute('data-end-date', tab.endDate);

                if (tab.active) {
                    currentStartDate = tab.startDate;
                    currentEndDate = tab.endDate;
                }

                container.appendChild(tabElement);
            });

            // 滚动到选中的标签
            setTimeout(() => {
                scrollToActiveTab();
            }, 100);
        }

        // 加载分类详情数据
        function loadCategoryDetailData() {
            // 获取当前选中的时间标签值
            const activeTimeTab = document.querySelector('.time-tab.active');
            const periodValue = activeTimeTab ? activeTimeTab.getAttribute('data-time') : (currentPeriodValue || '');

            const params = new URLSearchParams({
                category_id: categoryId,
                type: categoryType,
                level: categoryLevel,
                period_type: currentPeriod,
                period_value: periodValue
            });

            fetch(`{{ route('statistics.category-detail-data') }}?${params}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateSummaryData(data.data.summary);
                        updateTrendChart(data.data.trend);
                        updateRecordsList(data.data.records);
                        if (isLevel1) {
                            updateSubcategoriesData(data.data.subcategories);
                        }
                    } else {
                        console.error('加载数据失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('请求失败:', error);
                });
        }

        // 更新汇总数据
        function updateSummaryData(summary) {
            document.getElementById('category-total').textContent = parseFloat(summary.total_amount).toString();
            document.getElementById('category-count').textContent = summary.total_count;
            document.getElementById('category-avg').textContent = parseFloat(summary.avg_amount.toFixed(2)).toString();
        }

        // 更新趋势图
        function updateTrendChart(trendData) {
            const ctx = document.getElementById('trend-chart').getContext('2d');

            if (trendChart) {
                trendChart.destroy();
            }

            // 处理横坐标标签格式
            let processedLabels = trendData.labels.map(label => {
                if (currentPeriod === 'year') {
                    // 年统计：显示月份（1月、2月）
                    if (label.includes('-')) {
                        const month = parseInt(label.split('-')[1]);
                        return month + '月';
                    }
                    return label;
                } else if (currentPeriod === 'month') {
                    // 月统计：显示日期（1、2、3）
                    if (label.includes('-')) {
                        const day = parseInt(label.split('-')[2]);
                        return day.toString();
                    }
                    return label;
                } else if (currentPeriod === 'week') {
                    // 周统计：显示星期（周一、周二）
                    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
                    const date = new Date(label);
                    return weekdays[date.getDay()];
                }
                return label;
            });

            // 计算最高值
            const maxValue = Math.max(...trendData.amounts.filter(v => v !== null && v !== undefined));

            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: processedLabels,
                    datasets: [{
                        label: categoryName,
                        data: trendData.amounts,
                        borderColor: categoryType === 'income' ? '#10b981' : '#ef4444',
                        backgroundColor: 'transparent',
                        borderWidth: 2,
                        fill: false,
                        tension: 0,
                        pointRadius: 0,
                        pointHoverRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    layout: {
                        padding: {
                            top: 20,
                            right: 10,
                            bottom: 5,
                            left: 10
                        }
                    },
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.parsed.y;
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            grid: {
                                display: false
                            },
                            ticks: {
                                maxTicksLimit: 15,
                                font: {
                                    size: 10
                                },
                                color: '#9ca3af'
                            },
                            border: {
                                display: false
                            }
                        },
                        y: {
                            display: false,
                            beginAtZero: true,
                            grid: {
                                display: false
                            },
                            border: {
                                display: false
                            }
                        }
                    },
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    elements: {
                        line: {
                            borderJoinStyle: 'round'
                        }
                    }
                },
                plugins: [{
                    afterDraw: function(chart) {
                        if (maxValue > 0) {
                            const ctx = chart.ctx;
                            const chartArea = chart.chartArea;
                            const yScale = chart.scales.y;

                            // 绘制最高金额标注线
                            const yPosition = yScale.getPixelForValue(maxValue);

                            ctx.save();
                            ctx.strokeStyle = '#d1d5db';
                            ctx.lineWidth = 1;
                            ctx.setLineDash([5, 5]);
                            ctx.beginPath();
                            ctx.moveTo(chartArea.left, yPosition);
                            ctx.lineTo(chartArea.right, yPosition);
                            ctx.stroke();

                            // 绘制最高金额文字
                            ctx.fillStyle = '#6b7280';
                            ctx.font = '12px Arial';
                            ctx.textAlign = 'right';
                            ctx.fillText(maxValue.toString(), chartArea.right - 5, yPosition - 5);
                            ctx.restore();
                        }
                    }
                }]
            });
        }

        // 更新记录列表
        function updateRecordsList(records) {
            const recordsList = document.getElementById('records-list');

            // 排序记录
            let sortedRecords = [...records];
            if (currentSortType === 'amount') {
                sortedRecords.sort((a, b) => b.amount - a.amount);
            } else {
                sortedRecords.sort((a, b) => new Date(b.transaction_date) - new Date(a.transaction_date));
            }

            recordsList.innerHTML = '';

            sortedRecords.forEach((record, index) => {
                const recordElement = document.createElement('div');
                recordElement.className = `record-item ${!isExpanded && index >= 3 ? 'hidden' : ''}`;

                // 如果是一级分类页面且记录有二级分类名称，则显示二级分类名称
                let descriptionText = record.description || '';
                if (isLevel1 && record.sub_category_name) {
                    descriptionText = `[${record.sub_category_name}] ${descriptionText}`;
                }

                recordElement.innerHTML = `
                    <div class="record-info">
                        <div class="record-desc">${descriptionText}</div>
                        <div class="record-time">${record.transaction_date}</div>
                    </div>
                    <div class="record-amount ${record.type == 1 ? 'income' : 'expense'}">
                        ${parseFloat(record.amount).toString()}
                    </div>
                `;

                // 添加点击事件跳转到详情页面
                recordElement.style.cursor = 'pointer';
                recordElement.addEventListener('click', function() {
                    window.location.href = `/transaction/${record.id}`;
                });

                recordsList.appendChild(recordElement);
            });

            // 更新展开/收起按钮
            const toggleBtn = document.getElementById('toggle-btn');
            if (sortedRecords.length <= 3) {
                toggleBtn.style.display = 'none';
            } else {
                toggleBtn.style.display = 'block';
                toggleBtn.textContent = isExpanded ? '收起' : '查看更多';
            }
        }

        // 更新二级分类数据
        function updateSubcategoriesData(subcategories) {
            if (!isLevel1 || !subcategories.length) {
                document.getElementById('subcategory-ranking-section').style.display = 'none';
                return;
            }

            document.getElementById('subcategory-ranking-section').style.display = 'block';

            // 初始化饼图
            initSubcategoryPieChart(subcategories);

            // 更新颜色说明
            updateSubcategoryLegend(subcategories);

            // 更新排行榜
            updateSubcategoryRanking(subcategories);
        }

        // 初始化二级分类饼图
        function initSubcategoryPieChart(subcategories) {
            const ctx = document.getElementById('subcategory-pie-chart').getContext('2d');

            if (subcategoryPieChart) {
                subcategoryPieChart.destroy();
            }

            const colors = [
                'rgba(255, 99, 132, 0.7)',
                'rgba(54, 162, 235, 0.7)',
                'rgba(255, 206, 86, 0.7)',
                'rgba(75, 192, 192, 0.7)',
                'rgba(153, 102, 255, 0.7)',
                'rgba(255, 159, 64, 0.7)',
                'rgba(199, 199, 199, 0.7)',
                'rgba(83, 102, 255, 0.7)',
                'rgba(40, 159, 64, 0.7)',
                'rgba(210, 199, 199, 0.7)'
            ];

            subcategoryPieChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: subcategories.map(item => item.name),
                    datasets: [{
                        data: subcategories.map(item => item.amount),
                        backgroundColor: colors.slice(0, subcategories.length),
                        borderWidth: 0,
                        hoverBorderWidth: 2,
                        hoverBorderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '50%',
                    layout: {
                        padding: {
                            left: 10,
                            right: 10,
                            top: 10,
                            bottom: 10
                        }
                    }
                },
                plugins: [{
                    afterDraw: function(chart) {
                        const ctx = chart.ctx;
                        const chartArea = chart.chartArea;
                        const centerX = (chartArea.left + chartArea.right) / 2;
                        const centerY = (chartArea.top + chartArea.bottom) / 2;

                        // 计算总金额
                        const totalAmount = chart.data.datasets[0].data.reduce((sum, value) => sum + parseFloat(value), 0);

                        ctx.save();
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        // 绘制总金额
                        ctx.fillStyle = '#1e293b';
                        ctx.font = 'bold 18px Arial';
                        ctx.fillText(totalAmount.toString(), centerX, centerY - 8);

                        // 绘制"总计"标签
                        ctx.fillStyle = '#64748b';
                        ctx.font = '12px Arial';
                        ctx.fillText('总计', centerX, centerY + 12);

                        ctx.restore();
                    }
                }]
            });
        }

        // 更新二级分类总金额
        function updateSubcategoryTotalAmount(subcategories) {
            const totalAmount = subcategories.reduce((sum, item) => sum + parseFloat(item.amount), 0);
            const totalAmountElement = document.getElementById('subcategory-total-amount');
            if (totalAmountElement) {
                totalAmountElement.textContent = totalAmount.toString();
            }
        }

        // 更新二级分类颜色说明
        function updateSubcategoryLegend(subcategories) {
            const colors = [
                'rgba(255, 99, 132, 0.7)',
                'rgba(54, 162, 235, 0.7)',
                'rgba(255, 206, 86, 0.7)',
                'rgba(75, 192, 192, 0.7)',
                'rgba(153, 102, 255, 0.7)',
                'rgba(255, 159, 64, 0.7)',
                'rgba(199, 199, 199, 0.7)',
                'rgba(83, 102, 255, 0.7)',
                'rgba(40, 159, 64, 0.7)',
                'rgba(210, 199, 199, 0.7)'
            ];

            const legendContainer = document.getElementById('subcategory-legend');
            if (!legendContainer) return;

            legendContainer.innerHTML = '';

            subcategories.forEach((item, index) => {
                const legendItem = document.createElement('div');
                legendItem.className = 'legend-item';
                legendItem.innerHTML = `
                    <div class="legend-color" style="background-color: ${colors[index % colors.length]}"></div>
                    <div class="legend-text">${item.name}</div>
                `;
                legendContainer.appendChild(legendItem);
            });
        }

        // 更新二级分类排行榜
        function updateSubcategoryRanking(subcategories) {
            const subcategoryList = document.getElementById('subcategory-list');

            subcategoryList.innerHTML = '';

            // 按金额排序
            const sortedSubcategories = [...subcategories].sort((a, b) => b.amount - a.amount);

            sortedSubcategories.forEach((subcategory, index) => {
                const rank = index + 1;
                let rankClass = 'other';

                if (rank === 1) rankClass = 'top1';
                else if (rank === 2) rankClass = 'top2';
                else if (rank === 3) rankClass = 'top3';

                const subcategoryElement = document.createElement('div');
                subcategoryElement.className = 'ranking-item';
                subcategoryElement.innerHTML = `
                    <div class="ranking-rank ${rankClass}">${rank}</div>
                    <div class="ranking-info">
                        <div class="ranking-name">${subcategory.name}</div>
                        <div class="ranking-percent">${subcategory.percentage}%</div>
                    </div>
                    <div class="ranking-amount">
                        ${parseFloat(subcategory.amount).toString()}
                    </div>
                `;

                // 点击进入二级分类详情
                subcategoryElement.addEventListener('click', function() {
                    // 根据当前页面的周期类型和时间值构建URL参数
                    let periodType, periodValue;

                    if (currentPeriod === 'week') {
                        periodType = 'week';
                        periodValue = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${currentWeek}`;
                    } else if (currentPeriod === 'month') {
                        periodType = 'month';
                        periodValue = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
                    } else if (currentPeriod === 'year') {
                        periodType = 'year';
                        periodValue = currentYear.toString();
                    }

                    // 跳转到分类详情页面
                    const url = '{{ route("statistics.category-detail") }}' +
                                '?category_id=' + subcategory.id +
                                '&type=' + categoryType +
                                '&level=2' +
                                '&period_type=' + periodType +
                                '&period_value=' + periodValue;
                    window.location.href = url;
                });

                subcategoryList.appendChild(subcategoryElement);
            });
        }

        // 初始化事件监听
        function initEventListeners() {
            // 周期切换
            document.querySelectorAll('.period-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.period-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentPeriod = this.getAttribute('data-period');
                    // 重置为当前日期对应的年、月、周
                    const now = new Date();
                    currentYear = now.getFullYear();
                    currentMonth = now.getMonth() + 1;
                    currentWeek = Math.ceil(now.getDate() / 7);
                    // 重置周期值，让generateTimeTabs默认选择当前时间
                    currentPeriodValue = '';
                    generateTimeTabs();
                    initTimeTabsEventsOnly(); // 只重新绑定时间标签事件，不重复绑定导航按钮
                    // 更新时间显示
                    updatePeriodDisplay();
                    loadCategoryDetailData();
                });
            });

            // 添加导航按钮事件监听器（只添加一次）
            document.getElementById('prev-period').addEventListener('click', function() {
                navigatePeriod(-1);
            });

            document.getElementById('next-period').addEventListener('click', function() {
                navigatePeriod(1);
            });

            // 排序切换
            const sortBtn = document.getElementById('sort-btn');
            const sortMenu = document.getElementById('sort-menu');
            const sortText = document.getElementById('sort-text');

            sortBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const isVisible = sortMenu.style.display === 'block';
                sortMenu.style.display = isVisible ? 'none' : 'block';
            });

            document.querySelectorAll('.sort-option').forEach(option => {
                option.addEventListener('click', function() {
                    document.querySelectorAll('.sort-option').forEach(o => o.classList.remove('active'));
                    this.classList.add('active');

                    currentSortType = this.getAttribute('data-sort');
                    sortText.textContent = this.textContent;
                    sortMenu.style.display = 'none';

                    loadCategoryDetailData();
                });
            });

            // 点击其他地方关闭排序菜单
            document.addEventListener('click', function(e) {
                if (!sortBtn.contains(e.target) && !sortMenu.contains(e.target)) {
                    sortMenu.style.display = 'none';
                }
            });

            // 展开/收起按钮
            document.getElementById('toggle-btn').addEventListener('click', function() {
                isExpanded = !isExpanded;
                loadCategoryDetailData();
            });
        }

        // 更新时间显示
        function updatePeriodDisplay() {
            let displayText = '';

            if (currentPeriod === 'week') {
                displayText = `${currentYear}年${currentMonth}月第${currentWeek}周`;
            } else if (currentPeriod === 'month') {
                displayText = `${currentYear}年${currentMonth}月`;
            } else if (currentPeriod === 'year') {
                displayText = `${currentYear}年`;
            }

            const periodDisplayElement = document.getElementById('period-display');
            if (periodDisplayElement) {
                periodDisplayElement.innerHTML = displayText;
            }
        }

        // 导航到上一个或下一个大周期
        function navigatePeriod(direction) {
            if (currentPeriod === 'week') {
                // 周统计：跳转到上/下一个月
                currentMonth += direction;
                if (currentMonth > 12) {
                    currentMonth = 1;
                    currentYear++;
                } else if (currentMonth < 1) {
                    currentMonth = 12;
                    currentYear--;
                }
                currentWeek = 1; // 重置为第一周
            } else if (currentPeriod === 'month') {
                // 月统计：跳转到上/下一年
                currentYear += direction;
                currentMonth = 1; // 重置为1月
            } else {
                // 年统计：跳转到上/下5年
                currentYear += direction * 5;
            }

            // 重置周期值，让generateTimeTabs重新选择默认时间
            currentPeriodValue = '';

            // 重新生成时间标签
            generateTimeTabs();

            // 重新初始化时间标签事件（但不重复添加导航按钮事件）
            initTimeTabsEventsOnly();

            // 更新时间显示
            updatePeriodDisplay();

            // 重新加载数据
            loadCategoryDetailData();
        }

        // 初始化时间标签事件（包含导航按钮）- 已废弃，使用initTimeTabsEventsOnly代替
        function initTimeTabsEvents() {
            initTimeTabsEventsOnly();
            // 注意：导航按钮事件已在initEventListeners中绑定，此处不再重复绑定
        }

        // 只初始化时间标签事件（不包含导航按钮，避免重复绑定）
        function initTimeTabsEventsOnly() {
            document.querySelectorAll('.time-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.time-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');

                    // 更新当前时间范围
                    currentStartDate = this.getAttribute('data-start-date');
                    currentEndDate = this.getAttribute('data-end-date');
                    currentPeriodValue = this.getAttribute('data-time');

                    // 解析时间值以更新当前周期变量
                    if (currentPeriod === 'week') {
                        const parts = currentPeriodValue.split('-');
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                        currentWeek = parseInt(parts[2]);
                    } else if (currentPeriod === 'month') {
                        const parts = currentPeriodValue.split('-');
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                    } else {
                        currentYear = parseInt(currentPeriodValue);
                    }

                    // 更新时间显示
                    updatePeriodDisplay();

                    loadCategoryDetailData();
                });
            });
        }

        // 初始化页面
        function initPage() {
            // 根据URL参数设置当前周期
            const urlParams = new URLSearchParams(window.location.search);
            const periodType = urlParams.get('period_type');
            const periodValue = urlParams.get('period_value');

            // 处理period_type参数
            if (periodType && ['week', 'month', 'year'].includes(periodType)) {
                currentPeriod = periodType;

                // 更新页面上的period-tab按钮状态
                document.querySelectorAll('.period-tab').forEach(tab => {
                    tab.classList.remove('active');
                    if (tab.getAttribute('data-period') === periodType) {
                        tab.classList.add('active');
                    }
                });
            }

            // 处理period_value参数
            if (periodValue) {
                currentPeriodValue = periodValue;

                // 根据周期类型解析时间值
                if (currentPeriod === 'week') {
                    const parts = periodValue.split('-');
                    if (parts.length >= 3) {
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                        currentWeek = parseInt(parts[2]);
                    }
                } else if (currentPeriod === 'month') {
                    const parts = periodValue.split('-');
                    if (parts.length >= 2) {
                        currentYear = parseInt(parts[0]);
                        currentMonth = parseInt(parts[1]);
                    }
                } else if (currentPeriod === 'year') {
                    currentYear = parseInt(periodValue);
                }
            }

            // 兼容旧的period参数
            const period = urlParams.get('period');
            if (period && ['week', 'month', 'year'].includes(period) && !periodType) {
                currentPeriod = period;
            }

            // 生成时间标签
            generateTimeTabs();

            // 初始化事件监听器
            initEventListeners();
            initTimeTabsEventsOnly();

            // 更新时间显示
            updatePeriodDisplay();

            // 加载数据
            loadCategoryDetailData();
        }

        // 增强时间标签滑动功能
        function initTimeTabsScrolling() {
            const container = document.getElementById('time-tabs-container');
            const timeTabsElement = document.querySelector('.time-tabs');

            if (!container || !timeTabsElement) return;

            // 更新滑动指示器显示状态
            function updateScrollIndicators() {
                const canScrollLeft = container.scrollLeft > 0;
                const canScrollRight = container.scrollLeft < (container.scrollWidth - container.clientWidth);

                if (canScrollLeft) {
                    timeTabsElement.style.setProperty('--show-left-indicator', '1');
                } else {
                    timeTabsElement.style.setProperty('--show-left-indicator', '0');
                }

                if (canScrollRight) {
                    timeTabsElement.style.setProperty('--show-right-indicator', '1');
                } else {
                    timeTabsElement.style.setProperty('--show-right-indicator', '0');
                }
            }

            // 监听滚动事件
            container.addEventListener('scroll', updateScrollIndicators);

            // 初始化指示器状态
            setTimeout(updateScrollIndicators, 100);

            // 触摸滑动支持
            let isDown = false;
            let startX;
            let scrollLeft;

            container.addEventListener('mousedown', (e) => {
                isDown = true;
                container.style.cursor = 'grabbing';
                startX = e.pageX - container.offsetLeft;
                scrollLeft = container.scrollLeft;
            });

            container.addEventListener('mouseleave', () => {
                isDown = false;
                container.style.cursor = 'grab';
            });

            container.addEventListener('mouseup', () => {
                isDown = false;
                container.style.cursor = 'grab';
            });

            container.addEventListener('mousemove', (e) => {
                if (!isDown) return;
                e.preventDefault();
                const x = e.pageX - container.offsetLeft;
                const walk = (x - startX) * 2;
                container.scrollLeft = scrollLeft - walk;
            });

            // 设置初始光标样式
            container.style.cursor = 'grab';
        }

        // 页面加载完成后初始化
        window.addEventListener('load', function() {
            initPage();
            // 初始化滑动功能
            setTimeout(initTimeTabsScrolling, 200);
        });
    </script>
@endpush
